﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace eventr.View
{
    public partial class ImageOverlay : UserControl
    {
        bool visible = false;

        Model.AssetResult metaData;

        public ImageOverlay()
        {
            InitializeComponent();
            this.Loaded += (s, e) =>
            {
                KeyValuePair<int, object> item = (KeyValuePair<int, object>)DataContext;
                metaData = item.Value as Model.AssetResult;

                if (metaData != null)
                {
                    metaData.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(d_PropertyChanged);
                }
            };

            Media.MediaEnded += new RoutedEventHandler(Media_MediaEnded);

            updateStates(false);
            VisualStateManager.GoToState(this, "Visible", false);
        }

        void d_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (metaData.Viewed)
            {
                visible = true;
            }
            else
            {
                visible = false;
            }

            updateStates(true);
            configureMedia();
        }

        void updateStates(bool trans)
        {
            if (visible)
            {
                VisualStateManager.GoToState(this, "Visible", trans);
            }
            else
            {
                VisualStateManager.GoToState(this, "Invisible", trans);
            }
        }

        void configureMedia()
        {
            if (metaData.AssetType == "Video" && !string.IsNullOrEmpty(metaData.VideoUrl) && visible)
            {
                metaData.PauseSlideshow();

                Uri videoUri;

                if (metaData.VideoUrl.StartsWith("../"))
                {
                    videoUri = new Uri(Application.Current.Host.Source, metaData.VideoUrl);
                }
                else
                {
                    videoUri = new Uri(metaData.VideoUrl, UriKind.RelativeOrAbsolute);
                }

                Media.Source = videoUri;
                Media.Play();
            }
            else
            {
                visible = false;
                Media.Stop();
                Media.Source = null;
                updateStates(true);
            }
        }

        void Media_MediaEnded(object sender, RoutedEventArgs e)
        {
            visible = false;
            updateStates(true);
            metaData.ResumeSlideshow();
        }
    }
}
